///公共请求模块 添加

//目前支持可上传附件类型
const filesType = ["jpg", "jpeg", "png", "gif", "bmp", "mp4", "pdf", "md", "doc", "docx", "wps", "xls", "xlsx", "et", "ppt", "pptx", "dps", "vsdx", "rar", "zip", "7z"];

/**
 * 附件上传
 * @param {*附件} formFile 
 */
export const uploadFile = async function (formFile) {
    return $.ajax({
        "url": Utils.CurDomain.SysCfgUrl + "/yyattachments",
        "headers": {
            "Authorization": "Bearer " + Utils.GetSNAuthAT(),
            "Accept": "application/json"
        },
        "type": 'POST',
        "data": formFile,
        "enctype": 'multipart/form-data',
        "contentType": false,
        "processData": false,
        "cache": false,
        "async": false,
        "type": 'POST',
        "error": Utils.AjaxError
    });
}
/**
   * 根据图片id获取图片地址
   * @param {*图片id} id 
   * @returns 
   */
export const requestFilePath = async function (id) {
    return _request(`${Utils.CurDomain.SysCfgUrl}/yyattachments/${id}/url`, "GET");
}

//请求
const _request = async function (url, type, data) {
    return $.ajax({
        "url": url,
        "beforeSend": Utils.AjaxBeforeSend,
        "dataType": "json",
        "data": data,
        "type": type,
        "error": Utils.AjaxError
    });
}

/**
 * 判断附件类型是否可上传
 * @param {*附件} formFile 
 */
export const judgeUploading = (name, suffix) => {
    let attach = name.split('.').pop().toLowerCase(); //获取文件类型
    if (filesType.indexOf(attach) > 0) {
        if (suffix.indexOf(attach) > 0) {
            return {
                flag: true,
                name: name,
                type: attach
            };
        } else {
            return {
                flag: false,
                name: name,
                type: attach
            };
        }
    } else {
        return toastr.warning(`暂不支持${attach}类型文件上传`);
    }
}


/**
 * select2分页获取数据
 * @param {any select2 DOM} $select
 * @param {any 请求地址} url
 * @param {any 请求参数} fun
 *  orgId: $('#SelWorkshop').val(),
    searchInfo: params.term, // 搜索内容
    pageSize: 20,
    pageIndex: params.page || 0 //分页
 * @param {any 请求类型} type
 */
export const Select2Page = ($select, url, fun, type = 'GET', json = {}) => {
    let token = Utils.GetSNAuthAT()
    // if (url.indexOf(Utils.CurDomain.BaseCfgUrl) > -1 || url.indexOf(Utils.CurDomain.SaleUrl) > -1 || url.indexOf(Utils.CurDomain.BreedURL) > -1 || url.indexOf(Utils.CurDomain.MasterDataUrl) > -1 || url.indexOf(Utils.CurDomain.SubDataUrl) > -1 || url.indexOf(Utils.CurDomain.EmployeeMgtUrl) > -1) {
    //     token = Utils.Generate().split('&&&')[0];
    // } else {
    //     token = Utils.GetSNAuthAT()
    // }
    $select.select2({
        language: "zh-CN",
        ajax: {
            url: url,
            dataType: 'json',
            type: type,
            //beforeSend: Utils.AjaxBeforeSend,
            headers: {
                Authorization: "Bearer " + token,
                "Content-Type": 'application/json',
                Accept: 'application/json',
                "Access-Control-Allow-Origin": '*',
                "Access-Control-Allow-Headers": "X-Requested-With",
                "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS"
            },
            data: fun,
            processResults: function (data, params) {
                params.page = params.page || 1;
                let _data = data.data.items.map(item => {
                    item.text = item.name
                    return item;
                });
                return {
                    results: _data,// 后台返回的数据集
                    pagination: {
                        more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                    }
                };
            },
            delay: 700,//等待用户输入完后的 在等700毫秒 进行搜索
            minimumInputLength: 1,
        },
        ...json,


    });
}
//非分页请求
export const Select2Info = ($select, url, fun, type = 'GET', json = {}) => {
    $select.select2({
        language: "zh-CN",
        ajax: {
            url: url,
            dataType: 'json',
            type: type,
            beforeSend: Utils.AjaxBeforeSend,
            data: fun,
            processResults: function (data, params) {
                params.page = params.page || 1;
                let _data = data.data.map(item => {
                    item.text = item.name
                    return item;
                });
                return {
                    results: _data,// 后台返回的数据集
                    pagination: {
                        more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                    }
                };
            },
            minimumInputLength: 1,

        },
        ...json,


    });
}

/**
 * 判断附件名称长度
 * @param {*附件} file
 */
export const publicFileDraw = (file, thatFile, url) => {
    let formFile = new FormData();
    let href = window.location.pathname; //获取当前模块路径
    let arr = href.substr(href.indexOf("html")).split(/[/.]/g);

    if (file.name.length > 11) {
        let suffix = file.name.split('.').pop().toLowerCase(); //截取附件后缀
        let name = file.name.slice(0, 11 - (suffix.length) - 1); //计算截取文件的11位字符
        let _json = {
            title: '附件上传 - 名称超长提示',
            colorType: 'warning',
            content: `<p>附件名称【<span style="color:red"> ${file.name}</span>】长度超过11个字符，是否自动截取附件名称为【<span style="color:red"> ${name + '.' + suffix}</span>】?</p>`
        };
        if (url == 'rtbs') {
            Utils.DefinitionAffirm(_json, () => {

            }, undefined, "../../../../");
        } else if (url == 'account') {
            Utils.DefinitionAffirm(_json, () => {

            }, undefined, "../../");
        }
        else {
            Utils.DefinitionAffirm(_json, () => {

            });
        }

        //取消按钮
        $('.layui-layer-btn1').on('click', function () {
            thatFile.next().click();
            return toastr.warning('文件名称长度不能超过11个字符');
        });
        $('.layui-layer-close1').on('click', function () {
            thatFile.next().click();
            return toastr.warning('文件名称长度不能超过11个字符');
        });
    } else {
        let fileName = `${[arr[arr.length - 2]]}_${new Date().Format("yyyyMMdd")}_${file.name}`; //附件命名
        let imgFile = new File([file], fileName, { type: file.type });
        formFile.append('apiobjfile', imgFile);
        return formFile;
    }
}

/**
 * 用截取后的附件重新上传
 * @param {*附件} file
 */
export const sliceFileName = (upFiles) => {
    let suffix = upFiles.name.split('.').pop().toLowerCase(); //截取附件后缀
    let name = upFiles.name.slice(0, 11 - (suffix.length) - 1); //计算截取文件的11位字符
    return new File([upFiles], `${name + '.' + suffix}`, { type: upFiles.type });
}
